package com.example.newhabitclock

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout.LayoutParams
import android.widget.PopupWindow
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.transition.Visibility
import com.example.newhabitclock.HabitItemRecyclerViewPackage.HabitAdapter
import com.example.newhabitclock.HabitItemRecyclerViewPackage.HabitModel
import com.example.newhabitclock.databinding.FragmentCalendarItemBinding
import com.example.newhabitclock.databinding.FragmentMainBinding
import com.example.newhabitclock.databinding.ThreeDotDetailBinding
import java.time.LocalDate
import java.time.format.DateTimeFormatter

//向Room中插入数据，获取Room数据并配置recyclerView均在该界面实现
class MainFragment : Fragment() {
    private lateinit var mBinding: FragmentMainBinding
    private val mainViewModel: MainViewModel by viewModels()
    private lateinit var threeDotPopupViewBinding: ThreeDotDetailBinding  //右上角三个点图标点击后出现的弹窗
    private lateinit var calendarView: FragmentCalendarItemBinding  //右上角三个点图标中打卡日历的界面binding

    //创建用来保存习惯信息的HabitModelList集合
    private var myHabitModelList: ArrayList<HabitModel> = arrayListOf()

    //得到Adapter适配器类
    private lateinit var mRecyclerViewAdapter: HabitAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentMainBinding.inflate(layoutInflater)
        return mBinding.root
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val today = LocalDate.now()
        // 定义中文日期格式
        val formatter = DateTimeFormatter.ofPattern("yyyy年M月d日")
        // 格式化日期
        val formattedDate = today.format(formatter)
        //显示今天的日期
        mBinding.todayDateText.text = formattedDate

        //配置主界面的习惯卡片recyclerView中的数据
        //获取Room数据库中的数据并一一遍历
            mainViewModel.allHabits.observe(viewLifecycleOwner) { habitList ->
                //清空一遍，防止重复读取
                myHabitModelList.clear()

                //暂时没有创建习惯时，界面上就显示提醒文本
                if(habitList.isEmpty()){
                    mBinding.hideInfo.visibility = View.VISIBLE
                    mBinding.recyclerView.visibility = View.INVISIBLE
                }else{
                    mBinding.hideInfo.visibility = View.INVISIBLE
                    mBinding.recyclerView.visibility = View.VISIBLE
                }

                habitList.forEach { habit ->
                    //获取Room数据库中每个Habit的信息并配置HabitModel
                    //将配置好的HabitModel add到myHabitModelList:List<HabitModel>并传入recyclerView中进行配置
                    myHabitModelList.add(HabitModel(habit.name, habit.time, habit.repeatDays))
                }
                val infoList: List<HabitModel> = myHabitModelList
                //得到Adapter适配器类
                mRecyclerViewAdapter = HabitAdapter()

                //传入数据getData
                mRecyclerViewAdapter.getData(infoList)
                //传入ViewModel和lifeCycleOwner以供Adapter中修改Room数据库中的信息
                mRecyclerViewAdapter.getMainViewModel(mainViewModel, viewLifecycleOwner)

                //将Adapter适配器传给xmL中的recyclerView
                mBinding.recyclerView.adapter = mRecyclerViewAdapter
                //配置recyclerView的显示格式
                mBinding.recyclerView.layoutManager = LinearLayoutManager(
                    requireContext(),
                    LinearLayoutManager.VERTICAL,
                    false
                )
                //传输当前habit集合给Adapter
                mRecyclerViewAdapter.findCurrentHabitList(habitList)
            }.toString()

        //点击界面右下角的➕按钮跳转到添加习惯的界面
        mBinding.floatingActionButton.setOnClickListener {
            findNavController().navigate(R.id.action_mainFragment_to_addHabitFragment)
        }

        //添加习惯界面使用bundle传入习惯卡片的信息 接收传入的信息并插入这个habit到Room数据库中
        setFragmentResultListener("requestKey") { requestKey, bundle ->
            //获取用户输入的习惯信息
            val habitName = bundle.getString("name")
            val habitTime = bundle.getString("time")
            val habitRepeatDays = bundle.getStringArray("repeatDays")?.toList()

            if (habitName != null && habitTime != null && habitRepeatDays != null) {
                mainViewModel.insertHabit(habitName, habitTime, habitRepeatDays)
            }
        }

        //获取 点击右上角三个点后的弹窗binding(编辑习惯 打卡日历)
        threeDotPopupViewBinding = ThreeDotDetailBinding.inflate(layoutInflater)
        //获取 右上角三个点图标中 打卡日历 的界面binding
        calendarView = FragmentCalendarItemBinding.inflate(layoutInflater)

        val popupWindow = PopupWindow().apply {
            this.contentView = threeDotPopupViewBinding.root
            this.height = LayoutParams.WRAP_CONTENT
            this.width = LayoutParams.WRAP_CONTENT
            //弹窗外部可点击，true则点击外部隐藏弹窗
            this.isOutsideTouchable = true
            //弹窗界面可以获取焦点
            this.isFocusable = true
        }
        //点击主界面右上角的三个点(弹窗)
        mBinding.threeDot.setOnClickListener {
            //显示在右上角图标下方
            popupWindow.showAsDropDown(mBinding.threeDot)
        }

        //点击右上角弹窗中的 编辑习惯，打卡记录 功能
        threeDotPopupViewBinding.editHabit.setOnClickListener {  //编辑习惯功能
            mBinding.threeDot.visibility = View.INVISIBLE  //右上角三个点图标消失
            mBinding.backEditHabit.visibility = View.VISIBLE  //退出编辑图标显示
            //修改recyclerView中的具体视图显示与否
            mRecyclerViewAdapter.changeItemShowState(false)  //此时不用显示闹铃按钮 显示删除贴图吧·图标
            popupWindow.dismiss()
        }
        threeDotPopupViewBinding.checkInDetail.setOnClickListener {  //打卡记录功能
            findNavController().navigate(R.id.action_mainFragment_to_calendarHostFragment)
            popupWindow.dismiss()
        }

        //编辑习惯中：点击退出删除习惯功能
        mBinding.backEditHabit.setOnClickListener {
            //三个点，响铃按钮图标显示
            mBinding.backEditHabit.visibility = View.INVISIBLE
            mBinding.threeDot.visibility = View.VISIBLE
            //recyclerView中刷新配置使叉差，删除图标消失
            //调用recyclerView类中提供的方法
            mRecyclerViewAdapter.changeItemShowState(true)   //此时显示闹铃按钮 不显示删除贴图吧·图标
        }

    }
}